<?php
/**
 * CK 开发框架
 * User: Clake
 * Date: 2017/4/18
 * Time: 13:13
 */
namespace CK\Cache;

use CK\Util\Arr;

class Redis extends Cache {

    private $_conf = [
        'host'=>'127.0.0.1',
        'port'=>6379,
        'password'=>'123123',
        'db'=>0,
        'prefix'=>'ck_'
    ];

    private $_rd;
    private $_prefix;

    public function __construct($conf=null) {
        if ($conf) {
            $this->_conf = Arr::mrg($this->_conf,$conf);
        }
        $this->_rd = new \Redis();
        $this->_rd->connect($this->_conf['host'],$this->_conf['port'],2.0);
        $this->_rd->auth($this->_conf['password']);
        $this->_rd->select($this->_conf['db']);
        $this->_prefix = $this->_conf['prefix'];
    }

    /**
     * 选择DB
     * @param int $db
     */
    public function selectDB($db) {
        $this->_rd->select($db);
    }

    /**
     * 得到一个缓存
     * @param $key
     *
     * @return bool|string
     */
    public function get($key) {
        return json_decode($this->_rd->get($this->_prefix.$key),true);
    }

    /**
     * 设置一个缓存
     * @param     $key
     * @param     $value
     * @param int $expire
     *
     * @return bool
     */
    public function set($key, $value, $expire = 300) {
        if ($expire === 0) {
            return $this->_rd->set($this->_prefix.$key, json_encode($value));
        } else {
            return $this->_rd->set($this->_prefix.$key, json_encode($value), $expire);
        }
    }

    /**
     * 删除一个缓存
     * @param     $key
     * @param int $timeout
     *
     * @return bool
     */
    public function delete($key, $timeout = 0) {
        $this->_rd->delete($this->_prefix.$key);
        return true;
    }

    /**
     * 得到redis类
     * @return \Redis
     */
    public function rd() {
        return $this->_rd;
    }

    public function __destruct() {
        $this->_rd->close();
    }
}